package com.example.xwadmin.interceptor;


import com.example.xw.common.annotation.Allow;
import com.example.xw.common.entity.Admin;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AllowInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Allow allow = null;
        if (handler instanceof HandlerMethod){
            HandlerMethod m = (HandlerMethod) handler;
            allow = m.getMethodAnnotation(Allow.class);
            if(allow==null){
                return true;
            }
        }
        int minRole = allow.role();
        String pms = allow.pms();
        Admin admin = (Admin) request.getAttribute("cur_admin");
        if (admin.getLevel()<=minRole)
            return true;
        if ((","+admin.getPmses()+".").contains(","+pms+",")){
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        response.setStatus(403);
        response.getWriter().println("{\"code\":4001,\"data\":null,\"msg\":\"权限不足\"}");
        return false;
    }
}
